<?php
/**
 * 财付通接口类
 */
class Tenpay{
	
	private $config = null;

    function __construct($pays){
       
    	$this->config = $pays;
    }
    
    public function cfg($key){
    	
    	$rows = $this->config;
    	return $rows[$key];
    }

    /**
    * 生成支付代码
    * @param   array   $order  订单信息
    * @param   array   $pay    支付方式信息
    */
    function GetCode($order,$pay){
        
    	$cfg  = $this->config;
    	return $this->getCodeUrl($order,$cfg);
    }

    
    /**
     * 支付异步处理
     * @param   array   $order  订单信息
     * @param   array   $pay    支付方式信息
     */
    function notify($order,$pay){
		
    	$cfg  = $this->config;
    	return $this->notifyDeal($order,$cfg);
    }
	
	/**
	 * 支付返回处理
	 * @param $base 网站url根路劲
	 * @param $s 成功提示信息
	 * @param $f 失败提示信息
	 * @return Array
	 */
	function return_url($base,$s,$f){
		
		if($this->notify()){
			$url = "window.location.href='".$base.$this->surl."';";
			$info ="succeed";
			$msg = $s;
		}else{
			$url = "window.location.href='".$base.$this->furl."';";
			$info ="error";
			$msg = $f;
		}
		return array("url"=>$url,"msg"=>$msg,"info"=>$info);
	}


    /**
     * 处理订单成功
     */
    function success_db($order){
       
       //F("tenpay_success",$order);
       $order['addtime'] = time();
       $order['status']  = 1;
       $model = M("OrderPay");
       $model->add($order);
       
       $where = array("orderno"=>$order['orderno']); 
       M("Order")->where($where)->save(array("ispay"=>1));
       return $order['orderno'];
    }
	
    /**
     * 处理订单失败
     */
    function failure_db($order){

	   //F("tenpay_fail",$order);
       $order['addtime'] = time();
       $order['status']  = 2;
       $model = M("OrderPay");
       
       //$where = array("orderno"=>$order['orderno']); 
       //M("Order")->where($where)->save(array("ispay"=>2));
       return $order['orderno'];
    }

	function setReturnUrl($s,$f){
		$this->surl = $s;
		$this->furl = $f;
	}
	
	/**
	 * 通知处理
	 */
	function notifyDeal($order,$cfg){
		
		require ("Tenpay/classes/ResponseHandler.class.php");
		require ("Tenpay/classes/RequestHandler.class.php");
		require ("Tenpay/classes/client/ClientResponseHandler.class.php");
		require ("Tenpay/classes/client/TenpayHttpClient.class.php");
		$resHandler = new ResponseHandler();
		$resHandler->setKey($cfg['key']);
		
		//F("ResponseHandler",$resHandler->getAllParameters());
		//判断签名
		if($resHandler->isTenpaySign()) {
			//通知id
			$notifyid = $resHandler->getParameter("notify_id");
		
			//通过通知ID查询，确保通知来至财付通
			$queryReq = new RequestHandler();
			$queryReq->init();
			$queryReq->setKey($cfg['key']);
			$queryReq->setGateUrl($cfg['verifyurl']);
			$queryReq->setParameter("partner", $cfg['partner']);
			$queryReq->setParameter("notify_id", $notifyid);
			//通信对象
			$httpClient = new TenpayHttpClient();
			$httpClient->setTimeOut(5);
			
			//设置请求内容
			$httpClient->setReqContent($queryReq->getRequestURL());
			
			if($httpClient->call()) {
				//设置结果参数
				$queryRes = new ClientResponseHandler();
				$queryRes->setContent($httpClient->getResContent());
				$queryRes->setKey($cfg['key']);
				//F("ClientResponseHandler",$queryRes->getAllParameters());
				
				if($resHandler->getParameter("trade_mode") == "1"){
					
					//判断签名及结果（即时到帐）
					//只有签名正确,retcode为0，trade_state为0才是支付成功
					if($queryRes->isTenpaySign() && $queryRes->getParameter("retcode") == "0" && $resHandler->getParameter("trade_state") == "0") {
							
						$order['tradeno']  = $resHandler->getParameter("out_trade_no");//取结果参数做业务处理
						$order['dealno']   = $resHandler->getParameter("transaction_id");//财付通订单号
						$order['payfee']   = $resHandler->getParameter("total_fee");//金额,以分为单位
						//如果有使用折扣券，discount有值，total_fee+discount=原请求的total_fee
						$order['discount'] = $resHandler->getParameter("discount");
						$order['content']  = "[即时交易]处理成功";
						$order['trade']    = $resHandler->getParameter("trade_state");
						$order['type']     = 2;
						//处理数据库逻辑
						//注意交易单不要重复处理
						//注意判断返回金额
						$this->success_db($order);
		
					} else {
						//错误时，返回结果可能没有签名，写日志trade_state、retcode、retmsg看失败详情。
						$content ="[即时交易]验证签名失败 或 业务错误信息:trade_state=". $resHandler->getParameter("trade_state").",retcode=". $queryRes->getParameter("retcode").",retmsg=".$queryRes->getParameter("retmsg")."<br/>" ;
						$order['content'] = $content;
						$order['type']    = 2;
						$this->failure_db($order);
					}
				}elseif ($resHandler->getParameter("trade_mode") == "2"){
					//判断签名及结果（中介担保）
					//只有签名正确,retcode为0，trade_state为0才是支付成功
					if($queryRes->isTenpaySign() && $queryRes->getParameter("retcode") == "0" ){
						$order['orderno'] = $resHandler->getParameter("out_trade_no");//取结果参数做业务处理
						$order['dealno']  = $resHandler->getParameter("transaction_id");//财付通订单号
		
						//处理数据库逻辑
						//注意交易单不要重复处理
						//注意判断返回金额
						$order['type']    = 1;
						$order['trade']   = $resHandler->getParameter("trade_state");
						$order['content'] = "[中介担保]处理成功,交易状态".$order['trade'];
				
						$this->success_db($order);
					}else{
						
						$content = "[中介担保]验证签名失败 或 业务错误信息:trade_state=".$resHandler->getParameter("trade_state").",retcode=".$queryRes->getParameter("retcode").",retmsg=".$queryRes->getParameter("retmsg")."<br/>" ;
						$order['type']   = 1;
						$order['trade']  = 0;
						$order['content'] = $content;
						$this->failure_db($order);
					}
				}
			}else{
				$content = "<br>call err:".$httpClient->getResponseCode().",".$httpClient->getErrInfo()."<br>";
				$order['content'] = $content;
				$this->failure_db($order);		
			}
		} else{
			$content = $resHandler->getDebugInfo();
			$order['content'] = $content;
			$this->failure_db($order);
		}
	}
	
	/**
	 * 获取支付链接
	 */
	public function getCodeUrl($order,$cfg){
		
		require("Tenpay/classes/RequestHandler.class.php");		
		$strDate = date("Ymd");
		$strTime = date("His");

		$reqHandler = new RequestHandler();
		$reqHandler->init();
		$reqHandler->setKey($cfg['key']);
		$reqHandler->setGateUrl($cfg['gateway']);
		$order['total_fee'] = 1;
		//$order['total_fee'] = $order['total_fee']*100;
	
		//设置支付参数
		$reqHandler->setParameter("partner", $cfg['partner']); //*
		$reqHandler->setParameter("out_trade_no", $order['out_trade_no']);//*
		$reqHandler->setParameter("total_fee", $order['total_fee']);  //*总金额
		$reqHandler->setParameter("return_url", $cfg['return_url']); //*
		$reqHandler->setParameter("notify_url", $cfg['notify_url']); //*
		$reqHandler->setParameter("body", $cfg['subject']);
		$reqHandler->setParameter("bank_type", $cfg['bank_type']);  	  //*银行类型，默认为财付通
		$reqHandler->setParameter("spbill_create_ip", $_SERVER['REMOTE_ADDR']);//客户端IP
		$reqHandler->setParameter("fee_type", $cfg['fee_type']);               //*币种
		$reqHandler->setParameter("subject",$cfg['subject']);          //*商品名称，（中介交易时必填）
		
		//系统可选参数
		$reqHandler->setParameter("sign_type", $cfg['sign_type']);  	 	  //*签名方式，默认为MD5，可选RSA
		$reqHandler->setParameter("service_version", $cfg['service_version']); 	  //*接口版本号
		$reqHandler->setParameter("input_charset", $cfg['input_charset']);   	  //*字符集
		$reqHandler->setParameter("sign_key_index", "1");    	  //*密钥序号
		
		//业务可选参数
		$reqHandler->setParameter("attach", "");             	  //附件数据，原样返回就可以了
		$reqHandler->setParameter("product_fee", "");        	  //商品费用
		$reqHandler->setParameter("transport_fee", "0");      	  //物流费用
		$reqHandler->setParameter("time_start", date("YmdHis"));  //订单生成时间
		$reqHandler->setParameter("time_expire", "");             //订单失效时间
		$reqHandler->setParameter("buyer_id", "");                //买方财付通帐号
		$reqHandler->setParameter("goods_tag", "");               //商品标记
		$reqHandler->setParameter("trade_mode",$cfg['trade_mode']); // *交易模式（1.即时到帐模式，2.中介担保模式，3.后台选择（卖家进入支付中心列表选择））
		$reqHandler->setParameter("transport_desc","");           //物流说明
		$reqHandler->setParameter("trans_type",$cfg['trans_type']);              //*交易类型
		$reqHandler->setParameter("agentid",$cfg['agentid']);                  //*平台ID
		$reqHandler->setParameter("agent_type",$cfg['agent_type']);               //*代理模式（0.无代理，1.表示卡易售模式，2.表示网店模式）
		$reqHandler->setParameter("seller_id",$cfg['seller_id']);                //*卖家的商户号
		
		$reqUrl = $reqHandler->getRequestURL();
		$Info   = $reqHandler->getDebugInfo();
		$params = $reqHandler->getAllParameters();
		
		/* $html  = '<html><head><title>tenpay</title>';
		 $html .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head>';
		$html .= '<body onLoad="document.forms[\'gateway\'].submit();">';
		$html .= '<form action="'.$reqHandler->getGateUrl().'" method="post" name="gateway">';
		foreach($params as $k => $v) {
		$html .= '<input type="hidden" name="'.$k.'" value="'.$v.'" />';
		}
		$html  .= '</form></body></html>'; */
		
		$param = http_build_query($params);
		$url   = $reqHandler->getGateUrl()."?".$param;
		return $url;
	}
}